/**
 * @FileName: Receiver03.java
 * @Package: com.rabbitmq
 * @author lig134
 * @created 2017/3/9 13:47
 * <p>
 * Copyright 2015 ziroom
 */
package com.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * <p></p>
 *加入消息类型
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author lig134
 * @since 1.0
 * @version 1.0
 */
public class Receiver03 {

    public static void main(String[] args) throws InterruptedException, IOException, TimeoutException {

        ConnectionFactory connFac = new ConnectionFactory() ;

        connFac.setHost("master");
        connFac.setUsername("ligen");
        connFac.setPassword("ligen");
        Connection conn = connFac.newConnection() ;

        Channel channel = conn.createChannel() ;


        String exchangeName = "exchange02";

        //设置广播类型必须为direct.
        channel.exchangeDeclare(exchangeName, "direct") ;

        String queueName = channel.queueDeclare().getQueue() ;

        //第三个参数就是type，这里表示只接收type01类型的消息。
        channel.queueBind(queueName, exchangeName, "type01") ;
        //也可以选择接收多种类型的消息。只需要再下面再绑定一次就可以了
        channel.queueBind(queueName, exchangeName, "type02") ;


        //配置好获取消息的方式
        QueueingConsumer consumer = new QueueingConsumer(channel) ;
        channel.basicConsume(queueName, true, consumer) ;

        //循环获取消息
        while(true){

            //获取消息，如果没有消息，这一步将会一直阻塞
            QueueingConsumer.Delivery delivery = consumer.nextDelivery() ;

            String msg = new String(delivery.getBody()) ;

            System.out.println("received message[" + msg + "] from " + exchangeName);
        }

    }
}